package cfca.seal.web.action.sealmodel;

import cfca.sadk.util.Base64;
import cfca.seal.bean.AdminUser;
import cfca.seal.bean.OperationLog;
import cfca.seal.bean.SealImage;
import cfca.seal.common.Page;
import cfca.seal.exception.CodeException;
import cfca.seal.mananger.OperationLogManager;
import cfca.seal.util.FileUtil;
import cfca.seal.util.ImageUtil;
import cfca.seal.util.StringUtil;
import cfca.seal.web.service.OperationLogService;
import cfca.seal.web.service.SealModelService;
import cfca.seal.web.system.SessionManager;
import cfca.seal.web.vo.AutoSealModelVo;
import cfca.seal.web.vo.DoubleCircleModelVo;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping({"/sealmodel"})
public class SealModelAction
{
  private String jumpListPagePath = "sys/sealmodel/list.html";
  private String jumpDetailPagePath = "sys/sealmodel/detail.html";
  private String jumpEditPagePath = "sys/sealmodel/edit.html";
  private String jumpAddPagePath = "sys/sealmodel/add.html";
  private String jumpAutoAddPagePath = "sys/sealmodel/autoadd.html";
  private String jumpDoubleCircleAddPagePath = "sys/sealmodel/doubleadd.html";
  private String jumpAutoAddPreviewPagePath = "sys/sealmodel/previewImage.html";
  private String jumplistdo = "redirect:/sealmodel/v_list.do";
  private String applicationName = "印模管理";

  @Resource
  private SealModelService sealModelService;

  @Resource
  private OperationLogService operationLogService;
  private static final Logger logger = LoggerFactory.getLogger("web_sys");

  @RequestMapping({"/v_list"})
  public String getAll(SealImage sealImage, String pageNo, ModelMap modelMap, HttpServletRequest request) throws CodeException
  {
    try {
      AdminUser manager = SessionManager.getManager(request);
      Page page = this.sealModelService.getSealModels(sealImage, pageNo, manager);
      modelMap.put("page", page);
      modelMap.put("sealImage", sealImage);
      return this.jumpListPagePath;
    } catch (Exception e) {
      logger.error("查看印模列表出现系统错误", e);
      throw new CodeException("C0001", e);
    }
  }

  @RequestMapping({"/v_edit"})
  public String viewEditPage(String editId, ModelMap modelMap) throws CodeException {
    try {
      SealImage model = this.sealModelService.getSealModelById(editId);
      modelMap.put("sealmodel", model);
      return this.jumpEditPagePath;
    } catch (Exception e) {
      logger.error("编辑印模信息出现系统错误", e);
      throw new CodeException("C0001", e);
    }
  }

  @RequestMapping({"/v_add"})
  public String viewAddPage(ModelMap modelMap) throws CodeException {
    SealImage model = new SealImage();
    model.setId(StringUtil.generateID());
    modelMap.put("sealmodel", model);
    return this.jumpAddPagePath;
  }

  @RequestMapping({"/v_autoadd"})
  public String viewAutoAddPage(ModelMap modelMap) throws CodeException {
    return this.jumpAutoAddPagePath;
  }

  @RequestMapping({"/v_double"})
  public String viewDoubleCircleAddPage(ModelMap modelMap) throws CodeException {
    return this.jumpDoubleCircleAddPagePath;
  }

  @RequestMapping({"/v_detail"})
  public String viewDetailPage(String viewId, ModelMap modelMap, HttpServletRequest request) throws CodeException
  {
    try {
      SealImage model = this.sealModelService.getSealModelById(viewId);
      modelMap.put("sealmodel", model);
      return this.jumpDetailPagePath;
    } catch (Exception e) {
      logger.error("查看印模信息出现系统错误", e);
      throw new CodeException("C0001", e);
    }
  }

  @RequestMapping({"/o_autoadd"})
  public String autoAdd(String submitType, AutoSealModelVo sealModelVo, ModelMap modelMap, HttpServletRequest request) throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request, this.applicationName, "增加", "", "自动制作印模", null);
    operationLog.setOrganizationId(SessionManager.getManager(request).getOrganizationId());
    try
    {
      SealImage model = new SealImage();
      model.setId(StringUtil.generateID());
      operationLog.setObjectId(sealModelVo.getCode());
      model.setName(sealModelVo.getName());
      model.setCode(sealModelVo.getCode());
      model.setType(sealModelVo.getType());
      model.setImageHeight(sealModelVo.getImageHeight());
      model.setImageWidth(sealModelVo.getImageWidth());
      model.setOrganizationId(sealModelVo.getOrganizationId());
      model.setSealImageData(this.sealModelService.createImage(sealModelVo));
      model.setCreator(SessionManager.getId(request));
      boolean result = this.sealModelService.addSealModel(model);
      modelMap.put("resultInfo", Boolean.valueOf(result));
      return this.jumplistdo;
    } catch (Exception e) {
      operationLog.setResult(10);
      logger.error("添加印模信息出现系统错误", e);
      throw new CodeException("C0001", e);
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }
  }

  @RequestMapping({"/o_doubleadd"})
  public String doubleCircleAdd(String submitType, DoubleCircleModelVo sealModelVo, ModelMap modelMap, HttpServletRequest request) throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request, this.applicationName, "增加", "", "自动制作印模", null);
    operationLog.setOrganizationId(SessionManager.getManager(request).getOrganizationId());
    try
    {
      SealImage model = new SealImage();
      model.setId(StringUtil.generateID());
      operationLog.setObjectId(sealModelVo.getCode());
      model.setName(sealModelVo.getName());
      model.setCode(sealModelVo.getCode());
      model.setType(sealModelVo.getType());
      model.setImageHeight(sealModelVo.getImageHeight());
      model.setImageWidth(sealModelVo.getImageWidth());
      model.setOrganizationId(sealModelVo.getOrganizationId());
      model.setSealImageData(this.sealModelService.createDoubleCircle(sealModelVo));
      model.setCreator(SessionManager.getId(request));
      boolean result = this.sealModelService.addSealModel(model);
      modelMap.put("resultInfo", Boolean.valueOf(result));
      return this.jumplistdo;
    } catch (Exception e) {
      operationLog.setResult(10);
      logger.error("添加印模信息出现系统错误", e);
      throw new CodeException("C0001", e);
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }
  }

  @RequestMapping({"/o_add"})
  public String add(@RequestParam("sealImageFile") CommonsMultipartFile sealImageFile, SealImage model, ModelMap modelMap, HttpServletRequest request)
    throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request, this.applicationName, "增加", model.getCode(), "手工制作印模", null);
    operationLog.setOrganizationId(SessionManager.getManager(request).getOrganizationId());
    try
    {
      if (sealImageFile.isEmpty()) {
        throw new CodeException("C3039", "请选择印模图片");
      }
      if (!sealImageFile.getContentType().startsWith("image/")) {
        throw new CodeException("C3040", "请选择PNG格式的印模图片");
      }

      byte[] sealData = "".getBytes();
      sealData = FileUtil.getBytesFromInputStream(sealImageFile.getInputStream());
      sealData = ImageUtil.resizeImage(sealData, model.getImageWidth(), model.getImageHeight());
      sealData = ImageUtil.transferAlpha(sealData);
      model.setSealImageData(sealData);
      model.setCreator(SessionManager.getId(request));
      boolean result = this.sealModelService.addSealModel(model);
      modelMap.put("resultInfo", Boolean.valueOf(result));
      return this.jumplistdo;
    } catch (Exception e) {
      operationLog.setResult(10);
      logger.error("添加印模信息出现系统错误", e);
      throw new CodeException("C0001", e);
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }
  }

  @RequestMapping({"/o_edit"})
  public String edit(@RequestParam("sealImageFile") CommonsMultipartFile sealImageFile, SealImage model, ModelMap modelMap, HttpServletRequest request)
    throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request, this.applicationName, "修改", model.getCode(), "修改印模信息", null);
    operationLog.setOrganizationId(SessionManager.getManager(request).getOrganizationId());
    try
    {
      if ((!sealImageFile.isEmpty()) && (!sealImageFile.getContentType().startsWith("image/"))) {
        throw new CodeException("C3040", "请选择PNG格式的印模图片");
      }

      byte[] sealData = "".getBytes();
      if (!sealImageFile.isEmpty())
        sealData = FileUtil.getBytesFromInputStream(sealImageFile.getInputStream());
      else {
        sealData = this.sealModelService.getSealModelById(model.getId()).getSealImageData();
      }

      sealData = ImageUtil.resizeImage(sealData, model.getImageWidth(), model.getImageHeight());
      sealData = ImageUtil.transferAlpha(sealData);
      model.setSealImageData(sealData);

      boolean result = this.sealModelService.update(model);
      modelMap.put("resultInfo", Boolean.valueOf(result));
      return this.jumplistdo;
    } catch (Exception e) {
      operationLog.setResult(10);
      logger.error("编辑印模信息出现系统错误", e);
      throw new CodeException("C0001", e);
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }
  }

  @RequestMapping({"/o_delete"})
  public String delete(String deleteId, String code, ModelMap modelMap, HttpServletRequest request) throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request, this.applicationName, "删除", code, "删除印模信息", null);
    operationLog.setOrganizationId(SessionManager.getManager(request).getOrganizationId());
    try
    {
      boolean result = this.sealModelService.deleteById(deleteId);
      modelMap.put("resultInfo", Boolean.valueOf(result));
      return this.jumplistdo;
    } catch (Exception e) {
      operationLog.setResult(10);
      logger.error("删除印模信息出现系统错误", e);
      throw new CodeException("C0001", e);
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }
  }

  @RequestMapping({"/v_showSealImage"})
  public void showSealImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    SealImage sealImage = this.sealModelService.getSealModelById(request.getParameter("id"));
    if (sealImage != null) {
      byte[] bImage = sealImage.getSealImageData();
      OutputStream out = response.getOutputStream();
      out.write(bImage);
      out.flush();
      out.close();
    }
  }

  @RequestMapping({"/o_createAutoImage"})
  public String createAutoImage(String submitType, AutoSealModelVo sealModelVo, ModelMap modelMap, HttpServletRequest request) throws CodeException {
    String strImage = Base64.toBase64String(this.sealModelService.createImage(sealModelVo));
    modelMap.put("sealImage", strImage);
    modelMap.put("imageWidth", Integer.valueOf(sealModelVo.getImageWidth()));
    modelMap.put("imageHeight", Integer.valueOf(sealModelVo.getImageHeight()));
    return this.jumpAutoAddPreviewPagePath;
  }

  @RequestMapping({"/o_createDoubleCircle"})
  public String createDoubleCircleImage(String submitType, DoubleCircleModelVo sealModelVo, ModelMap modelMap, HttpServletRequest request) throws CodeException
  {
    String strImage = Base64.toBase64String(this.sealModelService.createDoubleCircle(sealModelVo));
    modelMap.put("sealImage", strImage);
    modelMap.put("imageWidth", Integer.valueOf(sealModelVo.getImageWidth()));
    modelMap.put("imageHeight", Integer.valueOf(sealModelVo.getImageHeight()));
    return this.jumpAutoAddPreviewPagePath;
  }

  @RequestMapping({"/o_output"})
  public void downloadSealImage(String id, HttpServletRequest request, HttpServletResponse response) throws CodeException {
    OutputStream outputStream = null;
    try {
      outputStream = new BufferedOutputStream(response.getOutputStream());
      SealImage sealImage = this.sealModelService.getSealModelById(id);
      String sealName = sealImage.getCode() + "_" + sealImage.getName() + ".png";
      byte[] sealImageData = sealImage.getSealImageData();

      response.reset();
      response.setContentType("text/html; charset=utf-8");
      response.addHeader("content-type", "application/x-msdownload;");
      response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sealName, "UTF-8"));
      response.addHeader("Content-Length", "" + sealImageData.length);
      outputStream.write(sealImageData);
      outputStream.flush();
    } catch (CodeException ce) {
      throw ce;
    } catch (Exception e) {
      throw new CodeException("C0001", "下载印模失败", e);
    } finally {
      try {
        if (outputStream != null)
          outputStream.close();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}